//
//  WBAuthorizeViewController.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/18.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBAuthorizeViewController: UIViewController {

    
    override func loadView() {
        
        view = webView
        webView.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)")
        print(url)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    override func viewDidLoad() {
        
        setUpUI()
    }
    
    // MARK: -  取消按钮的点击事件
    @objc private func clickCancel() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充按钮的点击事件
    @objc private func clickAutoAdd() {
        
        print("自动填充按钮被点击啦")
        let jsString = "document.getElementById('userId').value='\(UserName)';document.getElementById('passwd').value='\(PassWord)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: -  设置界面控件
    private func setUpUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "clickCancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "clickAutoAdd")
        navigationItem.title = "微博登录"
    }
    
    // MARK: -  懒加载webView
    private lazy var webView: UIWebView = UIWebView()
}


// MARK: -  webView的代理方法
extension WBAuthorizeViewController: UIWebViewDelegate {
    
    // MARK: -  webview将要加载url的时候会调用该方法  默认返回true   如果返回false  那么将不会加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /*
        Optional("https://api.weibo.com/oauth2/authorize?client_id=2070707421&redirect_uri=http://www.baidu.com#")
        Optional("https://api.weibo.com/oauth2/authorize")
        Optional("http://www.baidu.com/?code=634cf67f0e200ebd5d3c9c0029dea06a")
        Optional("https://m.baidu.com/?code=634cf67f0e200ebd5d3c9c0029dea06a&from=844b&vit=fps")
        */
        
        
        //判断前缀
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(Redirect_Uri) {
            
            //判断请求的参数是否存在
            if let param = request.URL?.query {
                
                let code = param.substringFromIndex("code=".endIndex)
                
                getUserAccount(code)
                
            }
        }
        
        
        return true
    }
    
    // MARK: -  开始加载webView的时候调用
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    // MARK: -  webView加载结束之后调用
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}

// MARK: -  获取accessToken
extension WBAuthorizeViewController{
    
    // MARK: -  获取accessToken
    func getUserAccount(code: String) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let param = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "redirect_uri": Redirect_Uri,
            "code": code,
        ]
        
        TMNetWorkTools.sharedTool .request("POST", urlString: urlString, param: param) { (response, error) -> () in
            
            if error != nil {
                
                print("错误\(error)")
                return
            }
            
            guard let dataDict = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            
            let account = WBUserAccountModel(dict: dataDict)
            
            // MARK: -  获取用户信息
            self.getUserInfo(account)
        }
    
        
    }
    
    // MARK: -  获取用户信息
    func getUserInfo(account: WBUserAccountModel) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token": account.access_token!,
            "uid": account.uid!
        ]

        TMNetWorkTools.sharedTool.request("GET", urlString: urlString, param: param) { (response, error) -> () in
            
            if error != nil {
                
                print("错误\(error)")
                return
            }
            
            guard let dataDict = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            
            account.screen_name = dataDict["screen_name"] as? String
            account.avatar_large = dataDict["avatar_large"] as? String
            
            //保存用户账户信息
            WBUserAccountTool.sharedAccountTool.saveData(account)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                //发送通知 切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchViewController, object: nil)
            })
        }
    }
}
